package cn.edu.zstu.qingzhu.qingzhushop.rabbitmq.consumer;

import cn.edu.zstu.qingzhu.qingzhushop.entity.User;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * FileName: BasicConsumer
 *
 * @Author: LvYibin
 * @Date: 2020/7/18 12:07
 * @Description:基本消息模型-生产者
 */

@Component
@RabbitListener(queues = "queue1",containerFactory = "singleListenerContainer")
public class BasicConsumer {
//    private static final Logger log = LoggerFactory.getLogger(BasicConsumer.class);
//    @Autowired
//    private ObjectMapper objectMapper;
//    @RabbitListener(queues = "${mq.basic.info.queue.name}",containerFactory = "singleListenerContainer")
//    @RabbitHandler
//    public void consumeMsg(@Payload byte[] msg){
//        try {
//            String message = new String(msg,"utf-8");
//            log.info("基本消息模型-消费者-监听消费到消息：{} ",message);
//            System.out.println("基本消息模型-消费者-监听消费到消息："+message);
//        }catch (Exception e){
//            log.error("基本消息模型-消费者-发生异常： ",e.fillInStackTrace());
//        }
//    }
private static final Logger log= LoggerFactory.getLogger(BasicConsumer.class);
    @Autowired
    private ObjectMapper objectMapper;

    /**
     * 监听并消费队列中的消息-在这里采用单一容器工厂实例即可
     */
    @RabbitHandler
    public void consumeMsg(@Payload byte[] msg){
        try {
            //String message=new String(msg, StandardCharsets.UTF_8);
            objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES,false);
            List<User> list = objectMapper.readValue(new String(msg, StandardCharsets.UTF_8),
                    new TypeReference<List<User>>(){/**/});
            log.info("基本消息模型-消费者-消费消息：{}",list);

        }catch (Exception e){
            log.error("基本消息模型-消费者-发生异常：",e.fillInStackTrace());
        }
    }
}
